﻿using HslCommunication;
using HslCommunication.ModBus;
using log4net;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ModbusApp
{
    public class ModbusClientHandler
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ModbusClientHandler));
        private ModbusTcpNet modbusTcpClient;
        private readonly byte _station;
        private readonly Config _config;
        private string ipAddress;
        private int writeInterval;
        private int writeCount;


        public ModbusClientHandler(Config config, byte station)
        {
            _config = config;
            this.ipAddress = config.ModbusIp;
            this.writeInterval = config.WriteInterval;
            this.writeCount = config.DeviceCount;
            modbusTcpClient = new ModbusTcpNet();
            _station = station;
        }

        // 连接到Modbus服务器
        public bool Connect()
        {
            modbusTcpClient.IpAddress = ipAddress;
            modbusTcpClient.Station = _station;
            modbusTcpClient.Port = _config.Port;
            var result = modbusTcpClient.ConnectServer();
            return result.IsSuccess;
        }

        // 启动后台线程，定时写入数据
        public async Task StartWriting(CancellationToken cancellationToken)
        {
            short loopInt = 0;
            short successSum = 0;
            short[] values = new short[_config.BatchCount];

            while (!cancellationToken.IsCancellationRequested)
            {
                if (loopInt > 10000) 
                    loopInt = 0;
                else
                    loopInt++;
                for (int i = 0; i < _config.BatchCount; i++)
                {
                    values[i] = (short)loopInt; // 每次递增
                }
                var result = modbusTcpClient.Write("x=3;0", values);
                if (!result.IsSuccess)
                {
                    Console.WriteLine($"time:{DateTime.Now},{_station}，值: {loopInt} NG");
                    log.Info($"time:{DateTime.Now},{_station}，值: {loopInt} NG");
                }
                else
                {
                    successSum++;
                    Console.WriteLine($"time:{DateTime.Now},{_station}，值: {loopInt} OK 插入数：{successSum}");
                    log.Info($"time:{DateTime.Now},{_station}，值: {loopInt} OK 插入数：{successSum}");
                }

                // 写入间隔
                await Task.Delay(writeInterval);
            }
        }
    }
}
